<?php

namespace App\Http\Controllers\Rbh;

use App\Exceptions\BusinessException;
use App\Http\Controllers\Controller;
use App\Models\MenuModel;
use App\Utils\ApiResponse;
use App\Utils\ControllerModelTrait;
use App\Utils\VerifyRequestInput;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class MenuController extends Controller
{
    use ApiResponse, VerifyRequestInput, ControllerModelTrait;

    const MENU_CACHE_KEY = 'rbhMenuAllList';

    /**
     * 菜单树形结构
     * @param Request $request
     * @return JsonResponse
     */
    public function getTree(Request $request): JsonResponse
    {
        $pagination = MenuModel::where('parent_id', 0)->orderBy('sort')->paginate($request->input('pageSize', 20));
        $collection = $pagination->getCollection();
        $list = [];
        foreach ($collection as $item) {
            $meta = $this->getMeta($item->meta);
            $item->meta = $meta;
            $item->children = $this->getLoopList($item->id);
            $list[] = $item;
        }
        return $this->success([
          'total'  => $pagination->total(),
          'page'   => $pagination->currentPage(),
          'page_size'  => $pagination->perPage(),
          'pages'  => $pagination->lastPage(),
          'list'   => $list
        ]);
    }

    /**
     * 保存数据
     * @param Request $request
     * @return JsonResponse
     */
    public function doSave(Request $request): JsonResponse
    {
        $data = $request->except(['created_at', 'updated_at', 'children']);
        $data['parent_id'] = $data['parent_id'] ?? 0;
        if ($request->input('path')) {
            $this->saveData(new MenuModel(), $data);
            self::setMenuCache();
        }
        return $this->success($data);
    }

    /**
     * 删除
     * @return JsonResponse
     * @throws BusinessException
     */
    public function doDelete(): JsonResponse
    {
        $ids = $this->verifyString('ids');
        $this->deleteData(new MenuModel(), $ids);
        self::setMenuCache();
        return $this->success([]);
    }

    /**
     * 迭代执行
     * @param $id
     * @return array
     */
    private function getLoopList($id): array
    {
        $collection = self::getMenuCache();
        $menus = $collection->where('parent_id', $id)->sortBy('sort');
        $data = [];
        foreach ($menus as $v) {
            $meta = $this->getMeta($v->meta);
            $v->meta = $meta;
            $v->children = $this->getLoopList($v->id);
            $data[] = $v;
        }
        return $data;
    }

    /**
     * 权限设置
     * @param $meta
     * @return mixed
     */
    private function getMeta($meta): mixed
    {
        if ($meta && $meta['guard'])
            $meta['guard'] = array_filter(explode(',', $meta['guard']));
        return $meta;
    }

    /**
     * 获取缓存
     * @return mixed
     */
    public static function getMenuCache(): mixed
    {
        if (!Cache::has(self::MENU_CACHE_KEY))
            self::setMenuCache();
        return Cache::get(self::MENU_CACHE_KEY);
    }

    /**
     * 设置缓存
     * @return void
     */
    public static function setMenuCache(): void
    {
        Cache::put(self::MENU_CACHE_KEY, MenuModel::all());
    }
}
